package com.heatup.apt.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.heatup.apt.api.controller.pay.util.PropertiesUtil;
import com.heatup.apt.api.service.UserService;
import com.heatup.apt.common.util.JsonClient;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.model.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录
 * Created by liuwanfen on 16/8/19.
 */
@Controller
@RequestMapping("/wechat")
public class WeChatLoginController extends BaseController{

	public static final Logger log = LoggerFactory.getLogger(WeChatLoginController.class);
	
    @Autowired
    private UserService userService;
    
    @ResponseBody
    @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
    private String login(HttpServletRequest request,HttpServletResponse response) {
        String code = RequestTools.RequestString(request,"code","");
        String state = "2";//RequestTools.RequestString(request,"state","/");
        String redirect = RequestTools.RequestString(request,"state","/");    
        
        try{
	        //获取openid
	        Map<String, String> map = new HashMap<String, String>();
	        
	        //todo: 放到配置文件中
	        map.put("appid", String.valueOf(PropertiesUtil.get("wechat_appid")).trim());//wx65db45e85c1be9c4
	        map.put("secret", String.valueOf(PropertiesUtil.get("wechat_secret")).trim());   //"3816ac8f220a3e9150fbab7321064d45"
	        map.put("code", code);
	        map.put("grant_type", "authorization_code");
	        JSONObject json = JsonClient.post(String.valueOf(PropertiesUtil.get("wechat_oaut2_url")).trim(), map);//https://api.weixin.qq.com/sns/oauth2/access_token
	        if(json.containsKey("errcode")){
	        	throw new Exception("get openid fail");
	        }
	        String accessToken = json.getString("access_token");
	        String openid = json.getString("openid");
	        String unionid = json.getString("unionid");        
       
	        
	        String urlUserInfo =String.valueOf(PropertiesUtil.get("wechat_userinfo_url")).trim() ; //"https://api.weixin.qq.com/cgi-bin/user/info";
	        if(state.equals("1")){
		        //获取token
		        //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
		        map.clear();
		        map.put("grant_type", "client_credential");
		        map.put("appid", String.valueOf(PropertiesUtil.get("wechat_appid")).trim());//"wx65db45e85c1be9c4");
		        map.put("secret", String.valueOf(PropertiesUtil.get("wechat_secret")).trim());//"3816ac8f220a3e9150fbab7321064d45");	
	        	json = JsonClient.post("https://api.weixin.qq.com/cgi-bin/token", map);
		        if(json.containsKey("errcode")){
		        	throw new Exception("get token fail");
		        }
		        accessToken = json.getString("access_token");
	        }else{
	        	urlUserInfo =String.valueOf(PropertiesUtil.get("wechat_sns_userinfo_url")).trim(); // "https://api.weixin.qq.com/sns/userinfo";
	        }
	        	
	        //获取用户信息
	        //https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN 	
	        //https://api.weixin.qq.com/sns/userinfo
	        map.clear();
	        map.put("access_token", accessToken);
	        map.put("openid", openid);
	        map.put("lang", "zh_CN");
	        json = JsonClient.post(urlUserInfo, map);
	        if(json.containsKey("errcode")){
	        	throw new Exception("get userinfo fail");
	        }
	        String nickname = json.getString("nickname"); 	
	        String headimgurl = json.getString("headimgurl");
	        String sex = json.getString("sex"); 		        
	        
	        UserInfo userInfo = userService.wechatLogin(openid, nickname, headimgurl, sex);
	        Integer isSubScribe = userService.isSubScribe(String.valueOf(userInfo.getId()));
	        userInfo.setSubscribe(isSubScribe);
	        if(userInfo != null){
	        	this.setUserInfo(userInfo);
	        	this.setUserId(userInfo.getId());
	        }

	        response.sendRedirect(redirect);
	        
	        return "login success:" + openid;
        }catch(Exception e){
        	e.printStackTrace();
        	log.error("微信登陆出错 --->" + e.toString() + e.getCause(),e);
        	return "error:" + e.getMessage();
        }
    }
  
 
}
